package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.1.1.1 $ $Date: 2006/12/11 23:43:17 $
 */

public final class ReasonCodesAction extends ChipTrackAction {


    // ----------------------------------------------------- Instance Variables

    private static final String ACTION_NAME = "/reasonCodes.do" ;  // Added by Basha (08/08/2003)

    // --------------------------------------------------------- Public Methods


    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if business logic throws an exception
     */
    public ActionForward execute(ActionMapping mapping,
				 ActionForm form,
				 HttpServletRequest request,
				 HttpServletResponse response)
	throws Exception {

            // Extract attributes and parameters we will need

			//System.out.println("ReasonCodesAction");
            DBTransaction dbt = null;
            String action = request.getParameter("action");
            String error_code = "";
            boolean success = false;
            //Bhaskar added the two lines given below 9 july 2003
            HttpSession session = request.getSession();
            User user = (User)session.getAttribute (SessionKeys.USER_KEY);
            // Added by Basha (08/08/2003)
            if(user == null)
            {
	            session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
                return (mapping.findForward ("login"));
            }
            // Added by Basha (08/08/2003)

            // Great Plains Sales Integration Re-direction -----------------------------------------

            if( user.isActionAllowed ( Functionality.REASON_CODE_SETUP,
            User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage" , "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage" , "TRUE" );
            }

            /** Commented by rohan on April 23rd 2004 as the integration is being done at the DAO level
            // Balaram on Jan 14, 2004
            if( Constants.FINANCE_INTEGRATION_TYPE_GREAT_PLAINS.equalsIgnoreCase( ConfigManager.getFinanceIntegrationType() ) == true )
            {
                return new GPReasonCodesAction().execute( mapping, form, request, response );
            }
            // Great Plains Re-direction -----------------------------------------------------------
            */

            //Errors
            HashMap errors = new HashMap();
            HashMap info = new HashMap();

            if((action != null) && (action.equals("Save"))) {
                String[] codeIds = request.getParameterValues("reason_code_id");
                String[] codes = request.getParameterValues("reason_code_no");
                String[] names = request.getParameterValues("reason_code_name");
                String[] types = request.getParameterValues("reason_code_type");

                // Added by Veeru on 10th Sep 2004
                String[] oldCodes = request.getParameterValues("old_reason_code_no");
                String[] oldTypes = request.getParameterValues("old_reason_code_type");
                String[] oldNames = request.getParameterValues("old_reason_code_name");

                String[] isNew    = request.getParameterValues("isNew");

               // System.out.println("Reason Codes = " + codeIds + " , " + codes + " ," + names);
                if(!isTokenValid(request))
                {
                    errors.put("This reason code is already saved, you can not save the same record again.","");
                    request.setAttribute("reasonCodes",SalesDAO.loadReasonCodes(null));
                    request.setAttribute("codeTypes", loadCodeTypes());
                    if(errors.size() != -1)
                    {
                        request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
                    }
                    return (mapping.findForward("success"));
                }
                try {

                    // Modified by Prabhanjan on 23rd Jan 2004. Added the If Condition.
                    // SalesDAO.saveReasonCodes ( codeIds, codes, names, types );
                    dbt = DBTransaction.getInstance();
                    if ( ( codeIds != null && codeIds.length > 0 ) && ( codes != null && codes.length > 0 ) && ( names != null && names.length > 0 ) && ( types != null && types.length > 0 ) )
                    {
                        //SalesDAO.saveReasonCodes ( codeIds, codes, names, types );

	                    dbt.begin();
                        error_code = SalesDAO.saveReasonCodes ( dbt, codeIds, codes, names, types, oldCodes, oldNames, oldTypes, isNew );
                        if ( "SUCCESS".equalsIgnoreCase(error_code))
                        {
                            success = true;
                        }
                        else
                        {
                            errors.put(error_code,"");
                        }
                    }
                    resetToken(request);
                } catch(Exception ex) {
                     errors.put(ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_REASON_CODES);
                     errors.put( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                     session.setAttribute( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Reason Code");
                     session.setAttribute( SessionKeys.ERROR_REPORT, ex );
                }
                finally
                {
                    if( success == true)
                    {
                        info.put( "Reason Codes", "Saved successfully" );
                        dbt.commit();
                    }
                    else
                    {
                        dbt.rollback();
                    }
                }
            }

            request.setAttribute("reasonCodes",SalesDAO.loadReasonCodes(null));
            request.setAttribute("codeTypes", loadCodeTypes());
            //System.out.println("Code Types = " + (ArrayList)request.getAttribute("codeTypes"));
			saveToken(request);

            /*
            request.setAttribute("marketingReasonCodes",SalesDAO.loadMarketingReasonCodes());
            request.setAttribute("salesReasonCodes",SalesDAO.loadSalesReasonCodes());
            request.setAttribute("financeReasonCodes",SalesDAO.loadFinanceReasonCodes());
            request.setAttribute("opsReasonCodes",SalesDAO.loadOpsReasonCodes());
              */
			if(errors.size() != -1)
			{
				request.setAttribute(SessionKeys.ERROR_MESSAGES, errors);
			}
			if(info.size() != -1)
			{
				request.setAttribute(SessionKeys.INFO_MESSAGES, info);
			}
            if((action != null) && (action.equals("Show")))
            {
                /*
                 Bhaskar added this if else block on 10 july 2003 to faciliate
                 the end user to understand that he cannot make any modifications
                 in that screen
                 */
                return (mapping.findForward("showReasonCodes"));
            }
            else
                return (mapping.findForward("success"));
    }

    public static ArrayList loadCodeTypes() throws Exception {
        ArrayList list = new ArrayList();
        list.add("OPERATIONS");
        list.add("FINANCE");
        list.add("SALES");
        list.add("MARKETING");

        return list;
    }

}
